package nl.hva.web.mvcwebapp.chat;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.List;
import nl.hva.web.mvcwebapp.chat.*;
import nl.hva.web.mvcwebapp.controllers.UserController;
import nl.hva.web.mvcwebapp.doa.CourseDAO;
import nl.hva.web.mvcwebapp.doa.UserDAO;
import nl.hva.web.mvcwebapp.models.Course;
import nl.hva.web.mvcwebapp.models.CourseUser;
import nl.hva.web.mvcwebapp.models.User;

public class LoginServlet extends HttpServlet {

    private String contextPath = "";

    /**
     * This method just redirects viewProfile to a login page.
     */
    @Override
    public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        contextPath = request.getContextPath();




        HttpSession session_user = request.getSession(true);
        String firstname = (String) session_user.getAttribute("user_firstname");
        String lastname = (String) session_user.getAttribute("user_lastname");
        String nickname = firstname + " " + lastname;
        if (firstname != null && lastname != null) {

            nickname = nickname.trim().toLowerCase();

            if ((nickname != null)) {
                try {
                    ChatRoomList roomlist = (ChatRoomList) getServletContext().getAttribute("chatroomlist");
                    boolean chatterexists = roomlist.chatterExists(nickname);
                    if (chatterexists) {
                        response.sendRedirect(contextPath + "/chat/login.jsp?d=t&n=" + nickname);
                    } else {
                        HttpSession session = request.getSession(true);
                        int timeout = 1800; // 30 minutes
                        String t = getServletContext().getInitParameter("sessionTimeout"); // gets Minutes
                        if (t != null) {
                            try {
                                timeout = Integer.parseInt(t);
                                timeout = timeout * 60;
                            } catch (NumberFormatException nfe) {
                            }
                        }
                        session.setMaxInactiveInterval(timeout);
                        session.setAttribute("nickname", nickname);
                        // Because Chatter objects are stored in room.
                        // So before viewProfile selects any room he is added to a temporary room "StartUp"
                        ChatRoom chatRoom = roomlist.getRoom("StartUp");
                        nickname = nickname.toLowerCase();
                        Chatter chatter = null;

                        chatter = new Chatter(nickname, new java.util.Date().getTime());

                        chatRoom.addChatter(chatter);

                        
                        response.sendRedirect(contextPath + "/chat/listrooms.jsp");

                    }
                } catch (Exception exception) {
                    System.out.println("Exception thrown in LoginServlet: " + exception.getMessage());
                    exception.printStackTrace();
                    response.sendRedirect(contextPath + "/chat/error.jsp");
                }
            } else {
                response.sendRedirect(contextPath + "/chat/login.jsp?ic=t");
            }

        }
        if (nickname == null) {

            response.sendRedirect(contextPath + "/chat/login_first.jsp");

        }
        if (firstname == null && lastname == null) {

            response.sendRedirect(contextPath + "/chat/login_first.jsp");

        }


    }

    /**
     * Performs some validation and if everything is ok sends viewProfile to a
     * page which displays a list of rooms available.
     */
    public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        System.out.println("tests");
        contextPath = request.getContextPath();
        String nickname = "";
        if (UserController.userAccountFirstName != "") {
            nickname = UserController.userAccountFirstName;
        } else {
            nickname = request.getParameter("nickname");
        }

        nickname = nickname.trim().toLowerCase();

        if ((nickname != null && nickname.indexOf(" ") == -1)) {
            try {
                ChatRoomList roomlist = (ChatRoomList) getServletContext().getAttribute("chatroomlist");
                boolean chatterexists = roomlist.chatterExists(nickname);
                if (chatterexists) {
                    response.sendRedirect(contextPath + "/chat/login.jsp?d=t&n=" + nickname);
                } else {
                    HttpSession session = request.getSession(true);
                    int timeout = 1800; // 30 minutes
                    String t = getServletContext().getInitParameter("sessionTimeout"); // gets Minutes
                    if (t != null) {
                        try {
                            timeout = Integer.parseInt(t);
                            timeout = timeout * 60;
                        } catch (NumberFormatException nfe) {
                        }
                    }
                    session.setMaxInactiveInterval(timeout);
                    session.setAttribute("nickname", nickname);
                    // Because Chatter objects are stored in room.
                    // So before viewProfile selects any room he is added to a temporary room "StartUp"
                    ChatRoom chatRoom = roomlist.getRoom("StartUp");
                    nickname = nickname.toLowerCase();
                    Chatter chatter = null;

                    chatter = new Chatter(nickname, new java.util.Date().getTime());
                    chatRoom.addChatter(chatter);

                    response.sendRedirect(contextPath + "/chat/listrooms.jsp");

                }
            } catch (Exception exception) {
                System.out.println("Exception thrown in LoginServlet: " + exception.getMessage());
                exception.printStackTrace();
                response.sendRedirect(contextPath + "/chat/error.jsp");
            }
        } else {
            response.sendRedirect(contextPath + "/chat/login.jsp?ic=t");
        }
    }
}